// pages/eat-report/eat-report.js
var wxCharts = require('../../utils/wxcharts.js');
var Api = require('../../utils/api.js');

// 定义环形图对象
var calorieRingChart = null;
var fatRingChart = null;
var carbohydrateRingChart = null;
var proteinRingChart = null;
var cholesterolRingChart = null;

Page({
  data: {
    date: "",
    calorieData: {
      "total": 0,
      "series": []
    },
    fatData: {
      "total": 0,
      "series": []
    },
    carbohydrateData: {
      "total": 0,
      "series": []
    },
    proteinData: {
      "total": 0,
      "series": []
    },
    eatScore: 0
  },

  onShareAppMessage(o) {},

  onLoad(e) {
    this.indexData();
  },
  
  onUnload() {
    // 页面卸载时清理图表实例
    calorieRingChart = null;
    fatRingChart = null;
    carbohydrateRingChart = null;
    proteinRingChart = null;
  },

  bindDate(e) {
    console.log(e);
    this.indexData({ "day": e.detail.value });
  },

  indexData: function(params) {
    var that = this;

    // 构建完整的URL，添加 detail=true 参数来获取营养数据分布
    let url = Api.eat(params);
    url += (url.includes('?') ? '&' : '?') + 'detail=true';

    wx.request({
      url: url,
      method: 'GET',
      success(res) {
        console.log("获取营养报告数据成功:", res.data);
        
        if (res.data && res.data.error_code) {
          wx.showToast({
            title: res.data.error_message,
            icon: 'none'
          });
          return;
        }
        
        // 使用后端返回的真实数据
        if (res.data) {
          that.setData({
            date: res.data.date || new Date().toLocaleDateString(),
            calorieData: res.data.calorieData || { total: 0, series: [] },
            fatData: res.data.fatData || { total: 0, series: [] },
            carbohydrateData: res.data.carbohydrateData || { total: 0, series: [] },
            proteinData: res.data.proteinData || { total: 0, series: [] },
            eatScore: res.data.eat_score || 0
          });
          
          console.log("设置营养数据:", that.data);
          that.ringCanvas();
        }
      },
      fail(err) {
        console.error("获取营养报告数据失败:", err);
        wx.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
        // 即使失败也绘制图表（显示空数据）
        that.ringCanvas();
      }
    });
  },

  ringCanvas: function() {
    var that = this;
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    // 使用延迟渲染，确保 canvas 组件已经准备好
    setTimeout(function() {
      try {
        console.log("开始渲染环形图...");
        console.log("热量数据:", that.data.calorieData);
        console.log("脂肪数据:", that.data.fatData);
        console.log("碳水数据:", that.data.carbohydrateData);
        console.log("蛋白质数据:", that.data.proteinData);
        
        calorieRingChart = that.createRingChart('calorieRingChart', that.data.calorieData.total, '热量(千卡)', that.data.calorieData.series, windowWidth);
        fatRingChart = that.createRingChart('fatRingChart', that.data.fatData.total, '脂肪(克)', that.data.fatData.series, windowWidth);
        carbohydrateRingChart = that.createRingChart('carbohydrateRingChart', that.data.carbohydrateData.total, '碳水(克)', that.data.carbohydrateData.series, windowWidth);
        proteinRingChart = that.createRingChart('proteinRingChart', that.data.proteinData.total, '蛋白质(克)', that.data.proteinData.series, windowWidth);
        
        console.log("所有环形图创建成功");
      } catch (e) {
        console.error("环形图渲染失败:", e);
      }
    }, 50);
  },

  createRingChart: function(canvasId, total, subtitle, series, windowWidth) {
    try {
      return new wxCharts({
        animation: true,
        canvasId: canvasId,
        type: 'ring',
        extra: {
          ringWidth: 25,
          pie: {
            offsetAngle: -45
          }
        },
        title: {
          name: total.toString(),
          color: '#7cb5ec',
          fontSize: 25
        },
        subtitle: {
          name: subtitle,
          color: '#666666',
          fontSize: 15
        },
        series: series,
        disablePieStroke: true,
        width: windowWidth,
        height: 300,
        dataLabel: true,
        legend: true,
        background: '#f5f5f5',
        padding: 0
      });
    } catch (e) {
      console.error('创建环形图失败:', canvasId, e);
      return null;
    }
  }
});
